package com.peng.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.peng.constant.Constants;
import com.peng.mapper.TCustomerMapper;
import com.peng.model.TCustomer;
import com.peng.query.CustomerQuery;
import com.peng.result.CustomerExcel;
import com.peng.result.R;
import com.peng.service.TCustomerService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class CustomerController {
    @Autowired
    private TCustomerService tCustomerService;

    @Autowired
    private TCustomerMapper tCustomerMapper;

    @PostMapping(value = "/api/clue/customer")
    public R convertCustomer(@ModelAttribute CustomerQuery customerQuery, @RequestHeader(value = "Authorization") String token) {
        customerQuery.setToken(token);
        Boolean convert = tCustomerService.convertCustomer(customerQuery);
        return convert ? R.OK() : R.FAIL();
    }

    @GetMapping(value = "/api/customers")
    public R convertCustomer(@RequestParam(value="current",required = false) Integer current) {
        if(current == null) {current = 1;}

        IPage<TCustomer> tCustomerIPage = tCustomerMapper.getCustomerByPage
                (new Page<TCustomer>(current, Constants.PAGE_SIZE));

        return R.OK(tCustomerIPage);
    }

    /**
     * 导出Excel
     *
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/api/exportExcel")
    public void exportExcel(HttpServletResponse response, @RequestParam(value = "ids", required = false) String ids) throws IOException {

        //要想让浏览器弹出下载框，你后端要设置一下响应头信息
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(Constants.EXCEL_FILE_NAME+System.currentTimeMillis(), StandardCharsets.UTF_8) + ".xlsx");

        //2、后端查询数据库的数据，把数据写入Excel，然后把Excel以IO流的方式输出到前端浏览器（我们来实现）

        List<Integer> idList = StringUtils.hasText(ids)
                                ? Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList())
                                : new ArrayList<>();

        List<CustomerExcel> dataList = tCustomerService.getCustomerByExcel(idList);

        EasyExcel.write(response.getOutputStream(), CustomerExcel.class)
                .sheet()
                .doWrite(dataList);
    }
}
